﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Gmis.Public
{
    public class CommonFunction
    {

        /// <summary>
        /// 获取Guid
        /// </summary>
        /// <returns></returns>
        public static string GetGuid()
        {
            return Guid.NewGuid().ToString().Replace("-", "");
        }

        public static string success()
        {
            return "{\"statusCode\":\"200\", \"message\":\"操作成功!!!\"}";
        }
        public static string success(string str, string navTabId)
        {
            return "{\"statusCode\":\"200\", \"message\":\"操作成功!" + str + "\",\"navTabId\":\"" + navTabId + "\"}";
        }
        /// <summary>
        /// 操作成功，关闭对话框，并刷新
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string successAndCloseCurrent(string str,string rel)
        {
            return "{\"statusCode\":\"200\", \"message\":\"操作成功!"+str+"\", \"navTabId\":\"\", \"callbackType\":\"closeCurrent\",\"forwardUrl\":\"\",\"rel\":\"" + rel + "\"}";
        }
        /// <summary>
        /// 操作成功，关闭弹出对话框，并刷新navTab页
        /// </summary>
        /// <param name="str"></param>
        /// <param name="rel">rel为空即可</param>
        /// <param name="navTabId">父页面ID</param>
        /// <returns></returns>
        public static string successAndCloseCurrent(string str,string rel,string navTabId)
        {
            return "{\"statusCode\":\"200\", \"message\":\"操作成功!" + str + "\", \"navTabId\":\"" + navTabId + "\", \"callbackType\":\"closeCurrent\",\"forwardUrl\":\"\",\"rel\":\"" + navTabId + "\"}";
        }

        public static string failure()
        {
            return "{\"statusCode\":\"300\", \"message\":\"操作失败\"}";
        }
        public static string failure(string str)
        {
            return "{\"statusCode\":\"300\", \"message\":\"操作失败!" + str + "\"}";
        }
        

        #region//获取Request的值 getRequestValue
        /// <summary>
        /// 获取Request值，Request有明的和暗的Request.Form两种，此处首先尝试明的，再尝试暗的，都找不到则返回默认值""。
        /// </summary>
        /// <param name="sRequest">Request的名称</param>
        /// <returns>返回Request值，为Null则返回默认值""</returns>
        public static string getRequestValue(string sRequest)
        {   //获取Request的值
            return getRequestValue(sRequest, "");
        }
        /// <summary>
        /// 获取Request值，Request有明的和暗的Request.Form两种，此处首先尝试明的，再尝试暗的，都找不到则返回默认值""。
        /// </summary>
        /// <param name="sRequest">Request的名称</param>
        /// <param name="sDefault">默认值</param>
        /// <returns>返回Request值，为Null则返回默认值""</returns>
        public static string getRequestValue(string sRequest, string sDefault)
        {   //获取Request的值
            System.Web.HttpRequest Request = HttpContext.Current.Request;
            string result = Request[sRequest];   //明Request
            if (string.IsNullOrEmpty(result)) result = Request.Form[sRequest];    //暗Request
            if (string.IsNullOrEmpty(result)) result = sDefault;
            if (string.IsNullOrEmpty(result)) result = "";
            return result;
        }
        #endregion

        #region//tryNullTo：强制转换默认值
        /// <summary>
        /// 强制转换默认值
        /// </summary>
        /// <param name="oValue"></param>
        /// <param name="oDefault"></param>
        /// <returns></returns>
        public static object tryNullTo(object oValue, object oDefault)
        {   //强制转换默认值
            try
            { if (oValue == null) return oDefault; else return oValue; }
            catch (Exception x)
            { return oDefault; }
        }
        public static string tryNullToString(object oValue, string oDefault)
        { return tryNullTo(oValue, oDefault).ToString(); }
        #endregion

        #region //varToIntDef：字符转成数字，失败返回默认值
        /// <summary>
        /// 字符转成数字Int整型，默认值
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="vDefault">默认值</param>
        /// <returns>转换成功则返回，失败则返回默认值</returns>
        public static int varToIntDef(object str, int vDefault)
        {   //
            int result = vDefault;
            if (str == null) return result;
            try
            { result = Convert.ToInt32(str); }
            catch (Exception x) { x = null; }
            //
            return result;
        }
        /// <summary>
        /// 字符转成数字Float，默认值
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="vDefault">默认值</param>
        /// <returns>转换成功则返回，失败则返回默认值</returns>
        public static double varToFloatDef(object str, double vDefault)
        {   //
            double result = vDefault;
            if (str == null) return result;
            try
            { result = Convert.ToDouble(str); }
            catch (Exception x) { }
            //
            return result;
        }
        /// <summary>
        /// 变量转换成string，默认值
        /// </summary>
        /// <param name="str">变量</param>
        /// <param name="vDefault">默认值</param>
        /// <returns>返回结果</returns>
        public static string varToStringDef(object str, string vDefault)
        {   //
            string result = vDefault;
            if (str == null) return result;
            try
            { result = str.ToString(); }
            catch (Exception x) { }
            //
            if (result == null) result = vDefault;
            return result;
        }
        /// <summary>
        /// 变量转换成dateTime，默认值
        /// </summary>
        /// <param name="str">变量</param>
        /// <param name="vDefault">默认值</param>
        /// <returns>返回结果</returns>
        public static DateTime? varToDateTimeDef(object str, DateTime? vDefault)
        {
            DateTime? result = vDefault;
            if (str == null) return result;
            //
            try
            { result = Convert.ToDateTime(str); }
            catch (Exception x) { }
            //
            if (result == null) result = vDefault;
            return result;
        }

        /// <summary>
        /// 变量转换成dateTime，默认值
        /// </summary>
        /// <param name="str">变量</param>
        /// <param name="vDefault">默认值</param>
        /// <returns>返回结果</returns>
        public static DateTime varToDateTimeDef(object str, DateTime vDefault)
        {
            DateTime result = vDefault;
            if (str == null) return result;
            //
            try
            { result = Convert.ToDateTime(str); }
            catch (Exception x) { }
            //
            if (result == null) result = vDefault;
            return result;
        }
        /// <summary>
        /// 值强制转化为逻辑型，如果出错，返回默认值
        /// </summary>
        /// <param name="value">要处理的值</param>
        /// <param name="vDefault">默认值</param>
        /// <returns></returns>
        public static bool varToBoolDef(object value, bool vDefault)
        {
            bool result = vDefault;
            if (value == null) return result;
            //
            try
            { result = Convert.ToBoolean(value); }
            catch (Exception x) { }
            //
            if (result == null) result = vDefault;
            return result;
        }
        #endregion

        #region 身份证验证以及获取出生日期，性别，年龄等信息
        /// <summary>
        /// 验证居民身份证编号码
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static bool CheckIDCard(string Id)
        {
            if (Id == null) return false;
            if (Id.Length == 18)
            {
                //bool check = CheckIDCard18(Id);
                bool check = ValidateVer2ID(Id);
                return check;
            }
            else if (Id.Length == 15)
            {
                bool check = CheckIDCard15(Id);
                return check;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 验证第二代身份证的合法性。
        /// <para>6位地址码，8位出生日期码；3位为顺序码；1位校验码。</para>
        /// <para>第17位（倒数第2位）为单数表示男性，双数表示女性。</para>
        /// <para>校验码取值范围是0至10，当值等于10时，用罗马数字符χ表示（以字母X代替）。</para>
        /// </summary>
        /// <param name="idCode">身份证号码</param>
        /// <returns></returns>
        public static bool ValidateVer2ID(string idCode)
        {
            try
            {
                if (idCode.Length == 18)
                {
                    // 1900-1-1 至 2099-12-31
                    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|71|(8[12])|91)\d{4}((((19)|(20))\d{2}(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19)|(20))\d{2}(0[13578]|1[02])31)|(((19)|(20))\d{2}02(0[1-9]|1\d|2[0-8]))|(((19)|(20))([13579][26]|[2468][048]|0[48])0229))\d{3}(\d|X|x)?$");
                    if (regex.IsMatch(idCode))
                    {
                        //验证生日是否是今天以前
                        DateTime birthday = new DateTime(int.Parse(idCode.Substring(6, 4)), int.Parse(idCode.Substring(10, 2)), int.Parse(idCode.Substring(12, 2)));
                        if (birthday <= DateTime.Today)
                        {
                            /* <<校验码>>
                             * 1.前17位数分别乘以不同的加权因子
                             * 2.相乘的结果相加
                             * 3.除以11，取余数
                             * 4.计算（12-余数）÷11的余数，如果余数等于10，则校验码为字母X
                             */
                            int[] factor = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; //加权因子

                            char[] fore17c = idCode.Remove(17).ToCharArray();
                            //int[] fore17i = Array.ConvertAll<char, int>(temp, new Converter<char, int>(c => int.Parse(c.ToString())));
                            int total = 0;
                            for (int i = 0; i < 17; i++)
                            {
                                total += int.Parse(fore17c[i].ToString()) * factor[i];
                            }
                            int mod = total % 11;
                            int checkCode = (12 - mod) % 11;
                            return (idCode.Substring(17, 1).ToUpper() == (checkCode == 10 ? "X" : checkCode.ToString()));
                        }
                    }
                }
            }
            catch
            {
                return false;
            }
            return false;
        }

        private static bool CheckIDCard18(string Id)
        {
            long n = 0;
            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = Id.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }
            return true;//符合GB11643-1999标准
        }

        private static bool CheckIDCard15(string Id)
        {
            long n = 0;
            if (long.TryParse(Id, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(Id.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birth = Id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证
            }
            return true;//符合15位身份证标准
        }

        /// <summary>
        /// 根据居民身份证编号获取生日
        /// </summary>
        /// <param name="IdCard"></param>
        /// <returns></returns>
        public static string GetBrithdayFromIdCard(string IdCard)
        {
            string rtn = "1900-01-01";
            if (IdCard.Length == 15)
            {
                rtn = IdCard.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            }
            else if (IdCard.Length == 18)
            {
                rtn = IdCard.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            }
            return rtn;
        }

        /// <summary>
        /// 根据身份证获取性别
        /// </summary>
        /// <param name="IdCard"></param>
        /// <returns></returns>
        public static string GetSexFromIdCard(string IdCard)
        {
            string rtn;
            string tmp = "";
            if (IdCard.Length == 15)
            {
                tmp = IdCard.Substring(IdCard.Length - 3);
            }
            else if (IdCard.Length == 18)
            {
                tmp = IdCard.Substring(IdCard.Length - 4);
                tmp = tmp.Substring(0, 3);
            }
            int sx = int.Parse(tmp);
            int outNum;
            Math.DivRem(sx, 2, out outNum);
            if (outNum == 0)
            {
                rtn = "女";
            }
            else
            {
                rtn = "男";
            }
            return rtn;
        }
        #endregion


        #region 获取图片路径
        /// <summary>
        /// 返回图片存储路径
        /// </summary>
        /// <returns></returns>
        public static string GetImagePath()
        {
            string header = System.Configuration.ConfigurationManager.AppSettings["URLHeader"].ToString();
            if (!header.EndsWith("/")) header += header;
            return header + "UpLoadFile/Image/";
        }

        /// <summary>
        /// 返回视频存储路径
        /// </summary>
        /// <returns></returns>
        public static string GetVideoPath()
        {
            string header = System.Configuration.ConfigurationManager.AppSettings["URLHeader"].ToString();
            if (!header.EndsWith("/")) header += header;
            return header + "UpLoadFile/Video/";            
        }

        /// <summary>
        /// 返回文档图片存储路径
        /// </summary>
        /// <returns></returns>
        public static string GetDocumentPath()
        {
            string header = System.Configuration.ConfigurationManager.AppSettings["URLHeader"].ToString();
            if (!header.EndsWith("/")) header += header;
            return header + "UpLoadFile/Document/";
        }

        /// <summary>
        /// 返回党员图片存储路径
        /// </summary>
        /// <returns></returns>
        public static string GetPMemberPath()
        {
            string header = System.Configuration.ConfigurationManager.AppSettings["URLHeader"].ToString();
            if (!header.EndsWith("/")) header += header;
            return header + "UpLoadFile/PMember/";
        }

        /// <summary>
        /// 返回党员图片存储路径
        /// </summary>
        /// <returns></returns>
        public static string GetVillagePath()
        {
            string header = System.Configuration.ConfigurationManager.AppSettings["URLHeader"].ToString();
            if (!header.EndsWith("/")) header += header;
            return header + "UpLoadFile/Village/";
        }

        /// <summary>
        /// 返回村委成员图片存储路径
        /// </summary>
        /// <returns></returns>
        public static string GetOrganizationPath()
        {
            string header = System.Configuration.ConfigurationManager.AppSettings["URLHeader"].ToString();
            if (!header.EndsWith("/")) header += header;
            return header + "UpLoadFile/Organization/";
        }

        /// <summary>
        /// 返回制度文件存储路径
        /// </summary>
        /// <returns></returns>
        public static string GetSystemPath()
        {
            string header = System.Configuration.ConfigurationManager.AppSettings["URLHeader"].ToString();
            if (!header.EndsWith("/")) header += header;
            return header + "UpLoadFile/System/";
        }
        #endregion
    }
}
